<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="getTitle" @ok="handleSubmit">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { accountFormSchema } from './data.data';
  import { codegenapi } from '../../system-api';
  //import { setCssVar } from '/@/logics/theme/util';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { TableActionType } from '/@/components/Table';

  export default defineComponent({
    name: 'AccountModal',
    components: { BasicModal, BasicForm },
    emits: ['success', 'register'],
    setup(_, { emit }) {
      const isUpdate = ref(true);
      const rowId = ref('');
      const { createMessage } = useMessage();
      const { success, warning, error } = createMessage;
      //const tableRef = ref<{ getDataSource: () => any; setColumns: (p: any) => void } | null>(null);
      const asynctableRef = ref<Nullable<TableActionType>>(null);
      //const tableSef = ref<{ setColumns: (p: any) => any } | null>(null);
      const [registerForm, { setFieldsValue, updateSchema, resetFields, validate }] = useForm({
        labelWidth: 100,
        schemas: accountFormSchema,
        showActionButtonGroup: false,
        actionColOptions: {
          span: 23,
        },
      });
      const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
        resetFields();
        setModalProps({ confirmLoading: false });
        isUpdate.value = !!data?.isUpdate;
        //console.log(posname);
        if (unref(isUpdate)) {
          setFieldsValue({
            ...data.record,
          });
        }

        //const treeData = await orgApi.sysOrgTreeGet();
        updateSchema([
          {
            field: 'id',
            show: unref(isUpdate),
            required: unref(isUpdate),
          },
        ]);
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      async function handleSubmit() {
        try {
          const values = await validate();
          setModalProps({ confirmLoading: true });

          //
          // TODO custom api

          let ret: any;
          if (!unref(isUpdate)) {
            ret = (await codegenapi.codeGenerateAddPost(values)).data;
          } else {
            ret = (await codegenapi.codeGenerateEditPost(values)).data;
          }

          if (ret != null) {
            if (ret.code == 204) {
              closeModal();
              success(ret.message);
            } else {
              warning(ret.message + ret.message[0].messages);
            }
          } else {
            error('未知错误');
          }

          if (unref(asynctableRef)) {
            // console.log('table data:', unref(asynctableRef)?.getDataSource());
          }

          //const [values, taskValues] = await Promise.all([validate(), validateTaskForm()]);
          //console.log('form data:', values, taskValues);

          emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
        } finally {
          setModalProps({ confirmLoading: false });
        }
      }

      return { registerModal, registerForm, getTitle, handleSubmit, asynctableRef };
    },
  });
</script>
